<?php
namespace app\common\model;
use app\common\model\BaseModel;
use think\Db;
/**
 * 
 */
class TableModel extends BaseModel
{
	public function fieldList($table_name)
	{
		return model('field')->where("table_name='".$table_name."'")->order('myorder asc,id asc')->select();
	}

	public function add($data)
	{
		$data_base=config('database.database');
		$data_pre=config('database.prefix');  
       	$tb_list = Db::query('show tables from '.$data_base);
       	$key='Tables_in_'.$data_base; 
       	foreach ($tb_list as $v) {
       		if ('cqz_'.$data['name']==$v[$key]) {
       			$this->error='数据表已存在'; 
       			return;
       		}
       	} 
		$res=$this->validate('Table.add')->allowField(true)->save($data); 
		if ($res) {
			$sql = "CREATE TABLE cqz_".$data['name']." (
			  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
			  `create_time` int(11) NOT NULL,
			  `active_time` int(11) NOT NULL,
			  `user_id` int(11) NOT NULL,
			  `is_admin` varchar(255) NOT NULL,
			  `status` tinyint(4) NOT NULL,
			  PRIMARY KEY (`id`)
			) ENGINE=MyISAM";
			Db::execute($sql);
			$this->createMV($data['name']);
			return 1;
		} 
	}


	public function edit($data)
	{
		$res=$this->isUpdate(true)->allowField(true)->save($data);
		if ($res) {
			if ($data['name']!=$data['old_name']) {
				Db::query("ALTER TABLE `cqz_".$data['old_name']."` RENAME `cqz_".$data['name']."`;");
			}
			return 1;
		}else{
			$this->error='失败';
		}
	}

	public function del($id)
	{
		$table_name=$this->getTName($id);
		$res=$this->where("id=".$id)->delete();
		if ($res) {
			$file_m=ROOT_PATH.'application/common/model/'.ucfirst($this->convertUnderline($table_name)).'Model.php';
			$file_v=ROOT_PATH.'application/common/validate/'.ucfirst($this->convertUnderline($table_name)).'Validate.php';
			$file_add_index=ROOT_PATH.'application/index/view/add_'.$table_name.'.html';
			$file_list_index=ROOT_PATH.'application/index/view/list_'.$table_name.'.html';
			$file_add_admin=ROOT_PATH.'application/admin/view/add_'.$table_name.'.html';
			$file_list_admin=ROOT_PATH.'application/admin/view/list_'.$table_name.'.html';

			if (file_exists($file_m)) {
				unlink($file_m);
			}
			if (file_exists($file_v)) {
				unlink($file_v);
			}
			if (file_exists($file_add_index)) {
				unlink($file_add_index);
			}
			if (file_exists($file_list_index)) {
				unlink($file_list_index);
			}
			if (file_exists($file_add_admin)) {
				unlink($file_add_admin);
			}
			if (file_exists($file_list_admin)) {
				unlink($file_list_admin);
			} 
			$sql='drop table cqz_'.$table_name;
			Db::execute($sql);
			model('field')->delTableField($table_name);
			return 1; 
		}else{
			return;
		}
	}

	// 生成模型文件
	public function createMV($table_name)
	{
		$name=$this->convertUnderline($table_name);
		$model_name=ucfirst($name).'Model';
		$validate_name=ucfirst($name).'Validate';
        $file_model=ROOT_PATH.'/application/common/model/'.$model_name.'.php';
        $file_validate=ROOT_PATH.'/application/common/validate/'.$validate_name.'.php';
		if (!file_exists($file_model)) {
        file_put_contents($file_model, "<?php
namespace app\common\model;
use app\common\model\BaseModel;
class ".$model_name." extends BaseModel
{  
	public function add(\$data)
	{
		\$res=\$this->isUpdate(false)->allowField(true)->save(\$data);
		if (\$res) {
			return 1;
		}else{ 
			return;
		}
	} 

	public function edit(\$data)
	{
		\$".$table_name."=\$this->find(\$data['id']);
		\$res=\$".$table_name."->isUpdate(true)->allowField(true)->save(\$data);
		if (\$res) {
			return 1;
		}else{
			return;
		}
	}

	public function del(\$id)
	{
		\$".$table_name."=\$this->find(\$id);
		\$res=\$".$table_name."->delete();
		if (\$res) {
			return 1;
		}else{
			return;
		}
	}
}", LOCK_EX);
           }

           if (!file_exists($file_validate)) {
            file_put_contents($file_validate, "<?php
namespace app\common\\validate; 
use think\Validate;

class ".$validate_name." extends Validate
{
    protected \$rule =   [
       
    ];
    protected \$msg =   [
        
    ];


    protected \$scene = [
         
    ];
    
}", LOCK_EX);
           }


	} 

	private function convertUnderline($str)
    {
      $str = preg_replace_callback('/([-_]+([a-z]{1}))/i',function($matches){
          return strtoupper($matches[2]);
      },$str);
      return $str;
    }

	private function getTName($table_id)
	{
		return db('table')->where("id=".$table_id)->value('name');
	}
}